package com.module04.work.demo04;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

    public static void main(String[] args) {

        ServerSocket ss = null;
        Socket s = null;
        ObjectInputStream ois = null;//获取输入流
        ObjectOutputStream oos = null;//获取输出流
        try {
            //1.创建ServerScoket对象提供端口号
            ss = new ServerSocket(8888);
            //2.等待客户端连接请求调用accpet方法
            System.out.println("等待客户端链接...");
            s = ss.accept();
            System.out.println("客户端连接成功！");
            //3.使用输出输出流进行通信
            ois = new ObjectInputStream(s.getInputStream());
            oos = new ObjectOutputStream(s.getOutputStream()
            );
            //接受客户端发送的对象内容
            UserMessage uMsg = (UserMessage) ois.readObject();
            //得到用户名
            String str1 = uMsg.getUser().getUserName();
            //得到密码
            String str2 = uMsg.getUser().getPassword();
            //判断用户名和密码是否正确并回发登录提示
            if (str1.equals("admin") && str2.equals("123456")) {
                uMsg.setType("success");
                oos.writeObject(uMsg);
            }else {
                uMsg.setType("fail");
                oos.writeObject(uMsg);
            }


        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            // 4.关闭Socket并释放有关的资源
            if (oos != null) {
                try {
                    oos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ois != null) {
                try {
                    ois.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }
}

